// 用于配置对应路由
let express = require('express')
let commentquery = require('../api/commnet_query')
let router = express.Router()
router.use(express.json());
router.use(express.urlencoded({
    extended: true
}));

// //获取所有评论信息
router.get('/', function (req, res) {
    res.redirect('/comments'); // 重定向
});
router.get('/comments', (req, res) => {
    commentquery.getall(function (rec) {
        res.json(rec).end();
    });
});

//获取指定name的评论信息 {通过id}
router.get('/comments/:comment_id', function (req, res) {
    var comment_id = parseInt(req.params.comment_id);
    commentquery.get(comment_id, function (rec) {
        res.json(rec).end();
    });
    console.log(comment_id);
});

//获取指定id的评论信息的原来数据 {通过id}
router.get('/comments/origin/:comment_id', function (req, res) {
    var comment_id = parseInt(req.params.comment_id);
    commentquery.getOrigin(comment_id, function (rec) {
        res.json(rec).end();
    });
    console.log(comment_id);
});
//使用POST方法添加评论信息
router.post('/comments', function (req, res) {
    var reqbody = req.body;
    console.log(reqbody);
    var arr = [];
    //遍历JSON数据中所有的值
    for (var key in reqbody) {
        arr.push(reqbody[key]);
    }
    commentquery.add([
        reqbody.fans_commnet,
        reqbody.all_commnet,
        reqbody.comment_state,
        reqbody.essay_id,
        reqbody.id
    ], function (rec) {
        res.json(rec).end();
    });
});
function fmObjToArr(data) {
    let arr = [];
    arr.push(data.fans_commnet);
    arr.push(data.all_commnet);
    arr.push(data.comment_state);
    arr.push(data.essay_id);
    arr.push(data.id);
    return arr;
}
//使用PUT方法修改评论信息 TODO
router.put('/comments/:comment_id', function (req, res) {
    var comment_id = parseInt(req.params.comment_id);
    console.log(comment_id,"comment_id");
    var reqbody = req.body;
    //先判断ID是否有效，再执行修改操作
    commentquery.getOrigin(comment_id, function (rec) {
        console.log(rec,"rec");
        if (rec.length == 0) {
            res.status(404).json({
                msg: '指定ID的评论不存在！'
            });
        } else {
            const newRequstBody = {
                ...rec[0],
                ...reqbody
            }
            commentquery.update(fmObjToArr(newRequstBody), function (rec) {
                res.json(rec).end();
            });
        }
    });
});
//使用DELETE方法删除评论信息
router.delete('/comments/:comment_id', function (req, res) {
    var comment_id = parseInt(req.params.comment_id);
    // var reqbody = req.body;
    //先判断ID是否有效，再执行删除操作
    commentquery.get(comment_id, function (rec) {
        if (rec.length == 0) {
            res.status(404).json({
                msg: '指定ID的流量不存在！'
            });
        } else {
            commentquery.del(comment_id, function (p) {
                res.json(rec).end();
            });
        }
    });
});
module.exports = router